#include "esp8266_webserver.hpp"

ESP8266WebServer webserver(80);         // 创建Web服务器对象，端口80

/**
 * 处理首页请求
 */
void handle_index()
{
    if (!LittleFS.exists("/index.html"))
    {
        Serial.println("文件 /index.html 不存在");
        webserver.send(404, "text/plain", "File not found");
        return;
    }
    // 读取并发送HTML文件
    File file = LittleFS.open("/index.html", "r");
    String content = file.readString();
    file.close();
    webserver.send(200, "text/html", content);
}

/**
 * 处理配置获取请求
 * 返回当前配置的JSON格式数据
 */
void handle_config()
{
    String json = "{";
    json += "\"wifi_ssid\":\"" + String(esp_config.wifi_ssid) + "\",";
    json += "\"wifi_password\":\"" + String(esp_config.wifi_password) + "\",";
    json += "\"mqtt_server\":\"" + String(esp_config.mqtt_server) + "\",";
    json += "\"mqtt_port\":" + String(esp_config.mqtt_port) + ",";
    json += "\"mqtt_user\":\"" + String(esp_config.mqtt_user) + "\",";
    json += "\"mqtt_password\":\"" + String(esp_config.mqtt_password) + "\",";
    json += "\"mqtt_pub_topic\":\"" + String(esp_config.mqtt_pub_topic) + "\",";
    json += "\"mqtt_sub_topic\":\"" + String(esp_config.mqtt_sub_topic) + "\",";
    json += "\"stopped\":" + String(esp_config.stopped);
    json += "}";
    webserver.send(200, "application/json", json);
}

/**
 * 处理配置保存请求
 * 从HTTP参数读取配置并保存到EEPROM
 */
void handle_save()
{
    strcpy(esp_config.wifi_ssid, webserver.arg("wifi_ssid").c_str());
    strcpy(esp_config.wifi_password, webserver.arg("wifi_password").c_str());
    strcpy(esp_config.mqtt_server, webserver.arg("mqtt_server").c_str());
    esp_config.mqtt_port = atoi(webserver.arg("mqtt_port").c_str());
    strcpy(esp_config.mqtt_user, webserver.arg("mqtt_user").c_str());
    strcpy(esp_config.mqtt_password, webserver.arg("mqtt_password").c_str());
    strcpy(esp_config.mqtt_pub_topic, webserver.arg("mqtt_pub_topic").c_str());
    strcpy(esp_config.mqtt_sub_topic, webserver.arg("mqtt_sub_topic").c_str());
    esp_config.stopped = atoi(webserver.arg("stopped").c_str());

    esp_saveconfig();                       // 保存配置到EEPROM

    String content = "{\"success\":true}";
    webserver.send(200, "application/json", content);
}

/**
 * Web服务器初始化
 */
void esp_webserver_init()
{
    webserver.on("/", handle_index);
    webserver.on("/config", handle_config);
    webserver.on("/save", handle_save);
    webserver.begin();
    LittleFS.begin();
}

/**
 * Web服务器运行处理
 */
void esp_webserver_running()
{
    webserver.handleClient();       // 处理客户端请求
}